import { onMounted, ref, watch } from 'vue'
import { VXETable } from 'vxe-table'
import dayjs from 'dayjs'
import { signalDataDelete, signalListEdit } from '@/api/singalManage'
import { RadarDelete, radarSingalEdit } from '@/api/radarsingalManage'
import Cookies from 'js-cookie'
import { displayUnitConversion, removeUnit } from '@/api/tool/filemanage'

export default function useList(listRequestFn, options, id, tableObject) {
  const ids = ref([])
  const {
    immediate = true,
    filterOption = ref({
      startTime: '',
      endTime: '',
      fileName: ''
    }),
    transformFn = undefined
  } = options

  // 区分雷达和通信
  const onlyId = id

  const $table = tableObject
  // 加载态
  const loading = ref(false)
  // 当前页
  const curPage = ref(1)
  // 总
  const total = ref(0)
  // 分页大小
  const size = ref(10)
  // 数据
  const list = ref([])

  const loadData = (
    pageNum = curPage.value,
    pageSize = size.value,
    startTime = filterOption.value.startTime,
    endTime = filterOption.value.endTime,
    fileName = filterOption.value.fileName
  ) => {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async resolve => {
      loading.value = true
      try {
        if (onlyId.value === 0) {
          const result = await listRequestFn({
            pageNum: pageNum,
            pageSize: pageSize,
            starttime: startTime,
            endtime: endTime,
            fileName: fileName
          })
          const transformResult = transformFn ? transformFn(result) : result
          const { data } = transformResult
          let count = 0
          list.value = data.rows
          total.value = data.total
          resolve({
            list: data,
            total: count
          })
        } else {
          const result = await listRequestFn({
            pageNum: pageNum,
            pageSize: pageSize,
            startTime: startTime,
            endTime: endTime,
            fileName: fileName
          })
          const transformResult = transformFn ? transformFn(result) : result
          const { data } = transformResult
          let count = 0
          list.value = data.rows
          total.value = data.total
          resolve({
            list: data,
            total: count
          })
        }
      } catch (error) {
        console.log(error)
      } finally {
        loading.value = false
        list.value.forEach((item, index) => {
          if ('radarNumber' in item) {
            item.listId = index + 1
            item.uploadTime = dayjs(item.uploadTime, 'YYYYMMDDHHmmss').format('YYYY-MM-DD HH:mm:ss')
            item.centerfreqIn = displayUnitConversion(item.centerfreqIn)
            item.samplerateIn = displayUnitConversion(item.samplerateIn)
            item.samplingBw = displayUnitConversion(item.samplingBw)
            item.intermediateFrequency = displayUnitConversion(item.intermediateFrequency)
            item.collectionTime == null ? 0 : item.collectionTime
          } else {
            item.listId = index + 1
            item.uploadTime = dayjs(item.uploadTime, 'YYYYMMDDHHmmss').format('YYYY-MM-DD HH:mm:ss')
            if (item.centerFreqIn != null) {
              item.centerFreqIn = displayUnitConversion(item.centerFreqIn)
            }
            if (item.intermediateFrequencyBandwidth != null) {
              item.intermediateFrequencyBandwidth = displayUnitConversion(
                item.intermediateFrequencyBandwidth
              )
            }
            if (item.samplingRate != null) {
              item.samplingRate = displayUnitConversion(item.samplingRate)
            }
            if (item.bitRate != null) {
              item.bitRate = displayUnitConversion(item.bitRate)
            } else {
              item.bitRate = '0KHz'
            }
          }
        })
      }
    })
  }
  const timeSearch = data => {
    if (!filterOption.value) {
      return
    } else {
      if (data.startTime === '') {
        filterOption.value.startTime = data.startTime
      } else {
        if ('startTime' in data) {
          filterOption.value.startTime = dayjs(data.startTime, 'YYYY-MM-DD').format('YYYYMMDD')
        }
      }
      if (data.endTime === '') {
        filterOption.value.endTime = data.endTime
      } else {
        if ('endTime' in data) {
          filterOption.value.endTime = dayjs(data.endTime, 'YYYY-MM-DD').format('YYYYMMDD')
        }
      }
      if (data.fileName === '') {
        filterOption.value.fileName = data.fileName
      } else {
        if ('fileName' in data) {
          filterOption.value.fileName = data.fileName
        }
      }
    }

    loadData()
  }

  //删除当前行
  const deleteCurrentLine = async row => {
    ids.value.push(row.id)
    const type = await VXETable.modal.confirm('您确定要删除该数据?')
    if (type === 'confirm') {
      if ($table) {
        $table.value.remove(row)
        if (onlyId.value === 0) {
          signalDataDelete(ids.value).then(() => {
            loadData()
            ids.value.splice(0)
          })
        } else {
          RadarDelete({ ids: ids.value.join(',') }).then(() => {
            loadData()
            ids.value.splice(0)
          })
        }
      }
    }
  }

  //批量删除
  const deleteAll = async () => {
    if (ids.value.length != 0) {
      const type = await VXETable.modal.confirm('您确定要删除该数据?')
      if (type === 'confirm') {
        if (onlyId.value === 0) {
          signalDataDelete(ids.value).then(() => {
            loadData()
            ids.value.splice(0)
          })
        } else {
          RadarDelete({ ids: ids.value.join(',') }).then(() => {
            loadData()
            ids.value.splice(0)
          })
        }
      }
    } else {
      VXETable.modal.message({ content: '请选择删除的数据', status: 'error' })
    }
  }

  //勾选框事件
  const selectChangeEvent = () => {
    const selectRecords = $table.value.getCheckboxRecords()
    selectRecords.forEach(item => {
      ids.value.push(item.id)
    })
    ids.value = Array.from(new Set(ids.value))
    if (selectRecords.length != ids.value.length) {
      ids.value = []
      selectRecords.forEach(item => {
        ids.value.push(item.id)
      })
    }
  }

  //获取当前行编辑的数据 => 修改接口
  const saveEdit = () => {
    let signalFile = {}
    const nowdata = $table.value.getUpdateRecords()
    if (onlyId.value === 0) {
      nowdata.forEach(item => {
        item.centerFreqIn != null
          ? (signalFile.centerfregInStr = item.centerFreqIn)
          : (signalFile.centerfregInStr = '0')
        item.intermediateFrequencyBandwidth != null
          ? (signalFile.bwInStr = item.intermediateFrequencyBandwidth)
          : (signalFile.bwInStr = '0')
        item.samplingRate != null
          ? (signalFile.samplerateInStr = item.samplingRate)
          : (signalFile.samplerateInStr = '0')
        item.bitRate != null
          ? (signalFile.coderateStr = item.bitRate)
          : (signalFile.coderateStr = '0')
        item.fileType != null ? (signalFile.fileType = item.fileType) : (signalFile.fileType = '0')
        item.dataOrganization != null
          ? (signalFile.dataOrganization = item.dataOrganization)
          : (signalFile.dataOrganization = '0')
        item.dataType != null ? (signalFile.dataType = item.dataType) : (signalFile.dataType = '0')
        item.startOffset != null
          ? (signalFile.startOffset = item.startOffset)
          : (signalFile.startOffset = '0')
        item.cutoffLength != null
          ? (signalFile.cutoffLength = item.cutoffLength)
          : (signalFile.cutoffLength = '0')
        item.debugMode != null
          ? (signalFile.debugMode = item.debugMode)
          : (signalFile.debugMode = '0')
        item.updateBy = Cookies.get('username')
        signalFile.id = item.id
        signalListEdit(signalFile).then(() => {
          loadData()
        })
      })
    } else {
      nowdata.forEach(item => {
        signalFile = { ...item }
        signalFile.fileTypeRadar = Number(item.fileTypeRadar)
        signalFile.collectionMethod = Number(item.collectionMethod)
        signalFile.centerfreqIn = removeUnit(item.centerfreqIn)
        signalFile.samplerateIn = removeUnit(item.samplerateIn)
        signalFile.samplingBw = removeUnit(item.samplingBw)
        signalFile.intermediateFrequency = removeUnit(item.intermediateFrequency)
        signalFile.uploadTime = dayjs(signalFile.uploadTime, 'YYYY-MM-DD HH:mm:ss').format(
          'YYYYMMDDHHmmss'
        )
        signalFile.updateBy = Cookies.get('username')
        radarSingalEdit(signalFile).then(() => {
          loadData()
        })
      })
    }
  }

  // 监听分页数据改变
  watch([curPage, size], () => {
    loadData(curPage.value)
  })

  onMounted(() => {
    if (immediate) {
      loadData(curPage.value)
    }
  })

  return {
    loading,
    curPage,
    total,
    list,
    filterOption,
    size,
    loadData,
    timeSearch,
    deleteCurrentLine,
    deleteAll,
    selectChangeEvent,
    saveEdit
  }
}
